<script setup>
import { ref } from 'vue'
import TitleComponent from '@/components/TitleComponent.vue'
import MdEditor from '@/components/MdEditor.vue'
import { Message } from '@arco-design/web-vue'
import { saveQuestion } from '@/api/question.js'
import router from '@/router/index.js'
import CodeEditor from '@/components/CodeEditor.vue'

const addForm = ref({
  title: '',
  content: '',
  tags: [],
  answer: '',
  prompt: [],
  judgeCase: [
    { input: '', output: '' }
  ],
  judgeConfig: {
    timeLimit: 0,
    memoryLimit: 0,
    stackLimit: 0
  }
})
const addFormRef = ref()
const addFormRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 1, max: 1000, message: '长度在 1 到 1000 个字符', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请输入标签', trigger: 'blur' }
  ],
  answer: [
    { required: true, message: '请输入答案', trigger: 'blur' },
    { min: 1, max: 1000, message: '长度在 1 到 1000 个字符', trigger: 'blur' }
  ],
  prompt: [
    { required: true, message: '请输入代码提示', trigger: 'blur' }
  ],
  judgeCase: [
    { required: true, message: '请输入测试用例', trigger: 'blur' }
  ],
  judgeConfig: [
    { required: true, message: '请输入判题配置', trigger: 'blur' }
  ]
}

const languages = ref(['java', 'c++', 'python'])
const currentLanguageIndex = ref(0)

const submitLoading = ref(false)

// 标签内容变化事件
const addFormTagsChange = (value) => {
  if (value.length > 5) {
    Message.warning('最多只能添加五个标签！')
    addForm.value.tags = value.slice(0, 5)
  }
}

// 题目内容变化事件
const onContentChange = (value) => {
  addForm.value.content = value
}
// 答案内容变化事件
const onAnswerChange = (value) => {
  addForm.value.answer = value
}

// 在指定位置添加测试用例
const addJudgeCase = (index) => {
  if (addForm.value.judgeCase.length < 100) {
    addForm.value.judgeCase.splice(index + 1, 0, { input: '', output: '' })
  } else {
    Message.warning('最多只能添加 100 个测试用例！')
  }
}

// 删除测试用例
const removeJudgeCase = (index) => {
  if (addForm.value.judgeCase.length > 1) {
    addForm.value.judgeCase.splice(index, 1)
  } else {
    Message.warning('至少需要一个测试用例！')
  }
}

// 测试用例输入变化事件
const onJudgeCaseInputChange = (index, value) => {
  addForm.value.judgeCase[index].input = value
}

// 测试用例输出变化事件
const onJudgeCaseOutputChange = (index, value) => {
  addForm.value.judgeCase[index].output = value
}

// 提交表单
const submitAddForm = () => {
  addFormRef.value.validate(async valid => {
    if (!valid) {
      try {
        submitLoading.value = true
        const res = await saveQuestion(addForm.value)
        if (res.data.code === 1) {
          Message.success('新增题目成功')
          router.back()
        }
      } catch (error) {
        console.error(error)
        Message.error('新增题目失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const changeCode = (value) => {
  const currentLanguage = languages.value[currentLanguageIndex.value]
  const existingPromptIndex = addForm.value.prompt.findIndex(p => p.language === currentLanguage)
  if (existingPromptIndex > -1) {
    addForm.value.prompt[existingPromptIndex].codePrompt = value
  } else {
    addForm.value.prompt.push({ language: currentLanguage, codePrompt: value })
  }
}

const handleTabChange = (index) => {
  currentLanguageIndex.value = index
}
</script>

<template>
  <div id="question-add-page">
    <a-card class="card">
      <TitleComponent title-text="新增题目" />
      <a-form :model="addForm" ref="addFormRef" :rules="addFormRules" layout="vertical" @submit="submitAddForm">
        <a-form-item label="题目标题" field="title" validate-trigger="blur">
          <a-textarea v-model="addForm.title" placeholder="请输入题目标题" :max-length="50"
                      show-word-limit />
        </a-form-item>
        <a-form-item label="题目标签" field="tags" validate-trigger="blur">
          <a-input-tag v-model="addForm.tags" placeholder="请输入标签(enter输入)"
                       allow-clear @change="addFormTagsChange"></a-input-tag>
        </a-form-item>
        <a-form-item label="题目内容" field="content" validate-trigger="blur">
          <MdEditor :value="addForm.content" :handleChange="onContentChange" style="width: 100%" />
        </a-form-item>
        <a-form-item label="题目答案" field="answer" validate-trigger="blur">
          <MdEditor :value="addForm.answer" :handleChange="onAnswerChange" style="width: 100%" />
        </a-form-item>
        <a-form-item label="代码提示" field="prompt" validate-trigger="blur">
          <a-tabs :default-active-key="currentLanguageIndex" @change="handleTabChange" style="width: 100%">
            <a-tab-pane v-for="(language, index) in languages" :key="index" :title="language">
              <CodeEditor
                :value="addForm.prompt.find(p => p.language === language)?.codePrompt || ''"
                :language="language"
                :handle-change="changeCode"
                style="width: 100%"
              />
            </a-tab-pane>
          </a-tabs>
        </a-form-item>
        <!-- 判题配置 -->
        <a-form-item label="判题配置" field="judgeConfig" validate-trigger="blur">
          <a-form-item label="时间限制（ms）" field="timeLimit" style="margin-right: 10px">
            <a-input-number
              v-model="addForm.judgeConfig.timeLimit"
              :min="0"
              placeholder="请输入时间限制"
            />
          </a-form-item>
          <a-form-item label="内存限制（B）" field="memoryLimit" style="margin-right: 10px">
            <a-input-number
              v-model="addForm.judgeConfig.memoryLimit"
              :min="0"
              placeholder="请输入内存限制"
            />
          </a-form-item>
          <a-form-item label="堆栈限制（B）" field="stackLimit">
            <a-input-number
              v-model="addForm.judgeConfig.stackLimit"
              :min="0"
              placeholder="请输入堆栈限制"
            />
          </a-form-item>
        </a-form-item>
        <a-form-item label="测试用例" field="judgeCase" validate-trigger="blur">
          <div class="judge-case-container">
            <div v-for="(caseItem, index) in addForm.judgeCase" :key="index">
              <a-card class="judge-case-card">
                <div class="case-number">{{ index + 1 }}</div>
                <a-form-item label="输入" :field="`judgeCase[${index}].input`"
                             validate-trigger="blur">
                  <a-textarea v-model="caseItem.input" placeholder="请输入测试用例输入"
                              :max-length="200"
                              show-word-limit
                              @change="onJudgeCaseInputChange(index, $event)" />
                </a-form-item>
                <a-form-item label="输出" :field="`judgeCase[${index}].output`"
                             validate-trigger="blur">
                  <a-textarea v-model="caseItem.output" placeholder="请输入测试用例输出"
                              :max-length="200"
                              show-word-limit
                              @change="onJudgeCaseOutputChange(index, $event)" />
                </a-form-item>
                <div class="judge-case-btn">
                  <a-button type="primary" long @click="addJudgeCase(index)">添加</a-button>
                  <a-button status="danger" long @click="removeJudgeCase(index)">删除</a-button>
                </div>
              </a-card>
            </div>
          </div>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" long html-type="submit" :loading="submitLoading">提交</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<style scoped>
.card {
  margin-top: 20px;
}

.judge-case-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.judge-case-card {
  width: calc((100% - 20px) / 3);
  min-width: 200px;
  position: relative;
}

.case-number {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
}

.judge-case-btn {
  width: 100%;
  display: flex;
  justify-content: space-between;
  gap: 10px;
}
</style>
